package Dom4jXML3;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 2.使用DOM解析第1题作业中编写的XML文档，输出所有学员信息，并进行以下操作：
 * 删除id为1的学生成绩信息，修改id为2的成绩为60，添加一个学生的成绩信息（id为5）。
 *
 * @author shkstart
 * @creat 2022-05-16:26
 */
public class XMLNodeOperate {
    public static final String FILEPATH = "Java_Senior\\d12\\date\\Scores.xml";
    private static Document getDoc(){
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
             doc = reader.read(new File(FILEPATH));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return doc;
    }

    private static void readNode() throws DocumentException {
//        SAXReader reader = new SAXReader();
//        Document doc = reader.read(new File(filePath));
        Document doc = getDoc();
        List<Node> nodes = doc.selectNodes("//student[@id]");
        System.out.println("学号\t\t姓名\t\t科目\t\t成绩");
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++");
        nodes.forEach(node -> {
            if (node instanceof Element) {
                Element element = (Element) node;
                String id = element.attributeValue("id");
                String name = element.elementTextTrim("name");
                String course = element.elementTextTrim("course");
                String score = element.elementTextTrim("score");
                System.out.println(id + "\t\t" + name + "\t\t" + course + "\t\t" + score);
                System.out.println("------------------------------------------");

            }
        });
    }
    private static void saveXML(Document document) throws IOException {

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(FILEPATH),format);
        writer.write(document);
        writer.flush();
        writer.close();

    }

    private static void addNode() {
        Document doc = getDoc();
        doc.getRootElement().addElement("student").addAttribute("id","5")
                .addElement("name").addText("蒋慎斌")
                .getParent().addElement("course").addText("SQL")
                .getParent().addElement("score").addText("90");
        try {
            saveXML(doc);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void updateNode() throws DocumentException {
        Document doc = getDoc();
        Element root = doc.getRootElement();
        List<Element> elements = root.elements("student");
        Element updEle = elements.stream().filter(element ->
                element.attributeValue("id").equals("2")).findFirst().orElse(null);
        updEle.element("score").setText("66");
        try {
            saveXML(doc);
            System.out.println("更新成功！！");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    private static void delNode() throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File(FILEPATH));
        List<Node> nodes = doc.selectNodes("//student[@id = '1']");
        nodes.forEach(node -> {
            if(node instanceof Element){
                Element element = (Element) node;
                element.getParent().remove(element);
            }
        });

        try {
            saveXML(doc);
            System.out.println("success!!");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        try {
            //查看原始数据
            readNode();
            //删除id=2的学生
            delNode();
            //输出xml文档
            readNode();
            //输出xml文档
            readNode();
            //更新xml文档
            updateNode();
            readNode();

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
